﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinFormsGraphicsDevice;
using TinyEngine.Core.Scene;
using TinyEngine.Core.Services;
using Microsoft.Xna.Framework;
using TinyEngine.Core.Camera;
using TinyEngine.Core;
using TinyEngine.Core.Renderer;
using TinyEngine.Core.Entities;
using Microsoft.Xna.Framework.Graphics;
using TinyEngine.Editor.Extensibility;

namespace TinyEngineEditor.SceneViewer
{
    public class SceneItemsGraphicsDeviceControl : BasicGraphicsDeviceControl
    {
        BasicCamera camera;
        
        IEntity selectedItem;
        
        public void SetItem(IEntity item)
        {
            selectedItem = item;
            this.Invalidate();
        }
        public SceneItemsGraphicsDeviceControl()
        {
            camera = new BasicCamera();
            camera.Zoom = 1;
            camera.Position = Vector3.Zero;
            camera.ViewPortSize = new Point(this.Width, this.Height);
            
            
        }
        public void MoveCamera(Vector3 vec)
        {
            camera.Position = vec;
            this.Invalidate();
        }
        
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            camera.ViewPortSize = new Point(this.Width, this.Height);
            camera.UpdateTransform();
        }

        protected override void Initialize()
        {
            base.Initialize();
         
        }
        protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseDown(e);
            this.Invalidate();

            if (EditorSession.Instance.sceneManager == null ||
                EditorSession.Instance.sceneManager.ActiveGameScene == null)
                return;

        }

        public void Reset()
        {
            selectedItem = null;

            Invalidate();
        }
        protected override void Draw()
        {
            base.Draw();

            
            if (selectedItem!=null)
            {
                var renderer = TinyEngine.Core.Services.ServiceManager.GetService<SpriteBatchService>();
                var scale = (float)this.Width / (float)selectedItem.BoundingRectangle.Width;
                camera.Zoom = scale;
                    
                
                if (selectedItem is IRenderable)
                {
                    
                    camera.Position = selectedItem.Position;
                    camera.UpdateTransform();
                    

                    renderer.Batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.Transform);
                    ((IRenderable)selectedItem).Draw(0);
                    renderer.Batch.End();
                }
                
            }

            
        }
    }
}
